﻿using Link_eLab.SqlSugar.Extension;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Configuration.ServerApi.Dao;
using Configuration.ServerApi.Entity;
using Configuration.ServerApi.Param;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Configuration.ServerApi.Service.Impl
{
    /// <summary>
    /// MaterialService
    /// </summary>
    public class MaterialService : IMaterialService
    {
        private readonly IConfiguration Configuration;
        private readonly IHttpContextAccessor Accessor;
        private readonly IBisMaterialDao BisMaterialDao;

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="accessor"></param>
        /// <param name="bisMaterialDao"></param>
        public MaterialService(IConfiguration configuration,
            IHttpContextAccessor accessor,
            IBisMaterialDao bisMaterialDao)
        {
            Configuration = configuration;
            Accessor = accessor;
            BisMaterialDao = bisMaterialDao;
        }

        #endregion 构造函数

        #region 获取材料数据列表

        /// <summary>
        /// 获取材料数据列表
        /// </summary>
        /// <param name="param">搜索条件</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> MaterialList(SearchModel param)
        {
            Console.WriteLine("\n获取材料数据列表：MaterialList");

            #region 获取登录用户相关信息

            string orgId = string.Empty;
            string userId = string.Empty;
            string userRoleId = string.Empty;
            try
            {
                orgId = Accessor.HttpContext.User.Claims.First(i => i.Type == "orgId").Value;
                userId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userId").Value;
                userRoleId = Accessor.HttpContext.User.Claims.First(i => i.Type == "userRoleId").Value;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "Token已过期, 请重新登录"
                });
            }

            #endregion

            // 初始化数据查询表达式
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.Append($" SELECT `id`,`builder_meta`,`nsites`,`elements`,`nelements`,`composition`,`composition_reduced`,`formula_pretty`,`formula_anonymous`,`chemsys`,`volume`,`density`,`density_atomic`,`symmetry`,`material_id`,`structure`,`deprecated`,`deprecation_reasons`,`initial_structures`,`task_ids`,`deprecated_tasks`,`calc_types`,`last_updated`,`created_at`,`origins`,`warnings`,`task_types`,`run_types`,`entries`,`fields_not_requested` FROM bis_material ");

            // 初始化查询条件
            strBuilder.Append($" WHERE 1=1 ");

            Console.WriteLine($"elements：{param.elements}");
            if (!string.IsNullOrEmpty(param.elements))
            {
                string temp_composition = param.elements.Replace("-", " ");
                strBuilder.Append($" AND `chemsys` LIKE concat('%', '{param.elements}', '%' ) OR `composition` LIKE concat('%', '{temp_composition}', '%') ");
            }

            // 分页查询
            strBuilder.Append($" LIMIT {param.Page.Value - 1},{param.Limit.Value} ");

            var result = await BisMaterialDao.QueryBySql<bis_material>(strBuilder.ToString());


            // 初始化数据查询表达式
            Expression<Func<bis_material, bool>> expression = w => true;

            Console.WriteLine($"elements：{param.elements}");
            if (!string.IsNullOrEmpty(param.elements))
            {
                string temp_composition = param.elements.Replace("-", " ");
                expression = expression.And(w => w.chemsys.Contains(param.elements) || w.composition.Contains(temp_composition));
            }

            var count = await BisMaterialDao.QueryCount(expression);

            return new JsonResult(new ResultModel
            {
                Count = count,
                Data = result
            });
        }

        #endregion

        #region 获取材料数据详情

        /// <summary>
        /// 获取材料数据详情
        /// </summary>
        /// <param name="param">搜索条件</param>
        /// <returns>JSON结果集</returns>
        public async Task<JsonResult> MaterialDetail(SearchModel param)
        {
            Console.WriteLine("\n获取材料数据详情：MaterialDetail");

            #region 参数校验

            Console.WriteLine($"Id：{param.Id}");
            if (string.IsNullOrEmpty(param.Id))
            {
                return new JsonResult(new ResultModel
                {
                    Success = false,
                    Msg = "必填参数不能为空"
                });
            }

            #endregion

            return new JsonResult(new ResultModel
            {
                Data = await BisMaterialDao.QuerySingle(w => w.id.Equals(param.Id))
            });
        }

        #endregion

    }
}